package com.heima.user.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.config.CacheService;
import com.heima.user.service.UserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import thread.AppThreadLocalUtil;

@Service
@Slf4j
@Transactional
public class UserRelationServiceImpl implements UserRelationService {

    @Autowired
    private CacheService cacheService;



    /**
     * 关注与取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult relation(UserRelationDto dto) {

        //1 参数校验
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        /**
         * 此时的userID去点赞别人的文章，是粉丝
         * 文章的作者id是被粉的人
         * 二者可以互粉
         */
        Integer userId = user.getId();
        Integer authorId = dto.getAuthorId();
        if (dto.getOperation() == 0) {
            // 用户关注了作者，用户是作者的粉丝，作者是我的关注
            // 添加用户的粉丝
            cacheService.zAdd("userFollow-" + userId,authorId.toString(),System.currentTimeMillis());
            // 添加作者的粉丝
            cacheService.zAdd("authorFans-"+ authorId,userId.toString(),System.currentTimeMillis());
        }else {
            // 取消关注，一方取消关注，则两方都要删除
            // 删除用户的关注
            cacheService.zRemove("userFollow-" + userId,authorId.toString());
            // 删除作者的粉丝
            cacheService.zRemove("authorFans-" + authorId,userId.toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
